package cn.innosmart.aq.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import cn.innosmart.aq.R;

/**
 * 局域网搜索结果列表适配器
 * Created by David on 2015/8/7.
 */
public class LanSearchResultAdapter extends BaseAdapter {
    private Context context;
    private LayoutInflater mInflater;
    private ArrayList<String> list;
    private int choosenPosition;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            choosenPosition = position;
            notifyDataSetChanged();
        }
    };

    /**
     * 构造函数
     *
     * @param context
     * @param results 搜索结果列表
     */
    public LanSearchResultAdapter(Context context, ArrayList<String> results) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
        this.list = results;
        this.choosenPosition = 0;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.listview_lansearch_result_list, null);
            holder.tvUid = (TextView) convertView.findViewById(R.id.tv_uid);
            holder.rbChoose = (RadioButton) convertView.findViewById(R.id.rb_choose);
            holder.rlBg = (RelativeLayout) convertView.findViewById(R.id.rl_bg);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String uid = list.get(position);
        holder.tvUid.setText(uid);
        if (position == choosenPosition) {
            holder.rbChoose.setChecked(true);
        } else {
            holder.rbChoose.setChecked(false);
        }
        holder.rbChoose.setTag(position);
        holder.rbChoose.setOnClickListener(onClickListener);
        holder.rlBg.setTag(position);
        holder.rlBg.setOnClickListener(onClickListener);
        return convertView;
    }

    //获得选中的结果Index，方便其他地方获得选中的搜索结果
    public int getChoosenPosition() {
        return choosenPosition;
    }

    public void setChoosenPosition(int choosenPosition) {
        this.choosenPosition = choosenPosition;
    }

    static class ViewHolder {
        TextView tvUid;
        RadioButton rbChoose;
        RelativeLayout rlBg;
    }
}
